Telegram Group & Telegram Channel
🐍 Задача по Python: Ловушка замыканий

Что выведет следующий код?


def create_funcs():
funcs = []
for i in range(3):
def f():
return i
funcs.append(f)
return funcs

for func in create_funcs():
print(func())


Варианты ответа:
A)

1
2


B)

2
2


C)

0
0


D) Ошибка выполнения


---

Правильный ответ: B

Почему:
Это классическая late binding: функция
f() не сохраняет значение i на момент создания, а берёт его из текущей области видимости при вызове.
К моменту вызова
i == 2 (последнее значение в range(3)), поэтому все три функции возвращают 2.

Чтобы избежать этого — можно использовать аргументы по умолчанию:
def f(i=i): return i



tg-me.com/pro_python_code/1781
Create:
Last Update:

🐍 Задача по Python: Ловушка замыканий

Что выведет следующий код?


def create_funcs():
funcs = []
for i in range(3):
def f():
return i
funcs.append(f)
return funcs

for func in create_funcs():
print(func())


Варианты ответа:
A)

1
2


B)

2
2


C)

0
0


D) Ошибка выполнения


---

Правильный ответ: B

Почему:
Это классическая late binding: функция
f() не сохраняет значение i на момент создания, а берёт его из текущей области видимости при вызове.
К моменту вызова
i == 2 (последнее значение в range(3)), поэтому все три функции возвращают 2.

Чтобы избежать этого — можно использовать аргументы по умолчанию:
def f(i=i): return i

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1781

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

The SSE was the first modern stock exchange to open in China, with trading commencing in 1990. It has now grown to become the largest stock exchange in Asia and the third-largest in the world by market capitalization, which stood at RMB 50.6 trillion (US$7.8 trillion) as of September 2021. Stocks (both A-shares and B-shares), bonds, funds, and derivatives are traded on the exchange. The SEE has two trading boards, the Main Board and the Science and Technology Innovation Board, the latter more commonly known as the STAR Market. The Main Board mainly hosts large, well-established Chinese companies and lists both A-shares and B-shares.

Start with a fresh view of investing strategy. The combination of risks and fads this quarter looks to be topping. That means the future is ready to move in.Likely, there will not be a wholesale shift. Company actions will aim to benefit from economic growth, inflationary pressures and a return of market-determined interest rates. In turn, all of that should drive the stock market and investment returns higher.

Python RU from kr


Telegram Python RU
FROM USA